package com.jmcgg.freesky.common.util;

public abstract class NumberSystemBean extends FreeskyBean {
	// number system Characters
	protected String nsChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx";
	protected int ns = 60; // number system
	protected String nst = "x"; // b=2; o=8; A=10; Z=36; x=60;
	protected String maxNS = "7E8E23JI0P2Y1"; // FIXME: it's now ns36

	public String getNSChar(long num) {
		int idx = 0;
		if (num >= 0)
			idx = (int) (num % ns);
		else
			idx = (int) ((-num) % ns);
		return nsChars.substring(idx, idx + 1);
	}

	public int getDecimalSingle(String nsChar) {
		if (nsChar == null || nsChar.trim().length() != 1)
			return -1; // NOT found, error input
		return nsChars.indexOf(nsChar);
	}

	public String getNSChars(long num) {
		String ret = "";
		long t = num;
		if (t < 0)
			t = -t;

		while (t >= ns) {
			ret = getNSChar((int) (t % ns)) + ret;
			t = t / ns;
		}
		// HERE the high bit should be put in front of others.
		ret = getNSChar((int) (t % ns)) + ret;
		return ret;
	}

	public long getDecimal(String nsChars) {
		long ret = 0;
		if (nsChars == null)
			return -1;
		String t = nsChars.trim();
		if (t.length() <= 1)
			return -1;

		// t = t.substring(1, t.length()); // don't have to remove the tag
		if (t.length() > maxNS.length()
				|| (t.length() == maxNS.length() && t.compareTo(maxNS) > 0)) {
			System.out.println("ERROR INPUT:" + nsChars
					+ " is too big for Long!");
			ret = -1;
		} else {
			int d = 0;
			while (t.length() > 1) {
				d = getDecimalSingle(t.substring(0, 1));
				if (d == -1)
					break;
				ret = ret * ns + d;
				t = t.substring(1);
			}

			if (d == -1) {
				System.out.println("ERROR INPUT:" + nsChars);
				ret = -1;
			} else {
				ret = ret * ns + getDecimalSingle(t.substring(0, 1));
			}
		}
		return ret;
	}

	public String getNSCharsTM() {
		return getNSChars(System.currentTimeMillis());
	}
}
